package com.mymail.factory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;

public class ConnectPools {
	static private final String DRIVER = "com.mysql.jdbc.Driver";
	static private final String USER = "mymail_manager";
	static private final String PASS = "weihua";
	static private final String URL = "jdbc:mysql://localhost/mymail?noAccessToProcedureBodies=true";
	static private int max=30;
	static private int min=3;
	static private int cur=0;
	static private ArrayList<Connection> pools=new ArrayList<Connection>();
	static {
		try {
			Class.forName(DRIVER);
			for(int i=0;i<min;++i){
				Connection con=Con();
				if(con!=null)pools.add(con);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} 
	}
	
	public static synchronized Connection getConnection(){
		if(pools.size()>0){
			cur++;
			return pools.remove(0);
		} else {
			if(cur>=max)return null;
			else {
				Connection con=Con();
				if(con!=null)cur++;
				return con;
			}
		}
	}
	
	private static synchronized Connection Con(){
		try {
			Connection con=DriverManager.getConnection(URL, USER, PASS);
			return con;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public synchronized void close(Connection con){
		while(pools.size()>min){
			try {
				pools.remove(0).close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(con!=null){
			pools.add(con);
			cur--;
		}
	}
	public synchronized void closeAll(){
		int size=pools.size();
		for(int i=0;i<size;++i){
			try {
				pools.remove(0).close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/*public static Connection getConnection() {
	  Connection con=null;
		try {
			con = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			return con;
		}
	}
	public static int getMax() {
		return max;
	}
	
	public static void close(Connection con) {
		try {
			if (con != null)
				con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	*/

	public static void setMax(int max) {
		ConnectPools.max = max;
	}
	
	public static int getMin() {
		return min;
	}
	
	public static void setMin(int min) {
		ConnectPools.min = min;
	}
	

}
